package top.kaoshanji.ch02.serialClone;

import java.io.*;

/**
 * author kaoshanji
 * ^_^
 * create time 2024/12/6 17:19
 */
public class SerialCloneable implements Cloneable, Serializable {

    public Object clone() throws CloneNotSupportedException {

        try {

            // 将对象保存到字节数组里
            var bout = new ByteArrayOutputStream();
            try (var out = new ObjectOutputStream(bout)){
                out.writeObject(this);
            }

            // 通过读取字节数组实现拷贝一个对象
            try (var bin = new ByteArrayInputStream(bout.toByteArray())){
                var in = new ObjectInputStream(bin);
                return in.readObject();
            }

        } catch (IOException | ClassNotFoundException e) {
            var e2 = new CloneNotSupportedException();
            e2.initCause(e);
            throw e2;
        }

    }


}
